package hu.issue.ejb;

import hu.issue.entity.Milestone;
import hu.issue.entity.Project;
import hu.issue.exceptions.ProjectNotFoundException;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class ProjectServiceBean implements ProjectService {
	@PersistenceContext
	private EntityManager manager;

	@Override
	public void createProject(final Project project) {
		this.manager.persist(project);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Project> getProjects() {
		final Query query = this.manager.createQuery("select p from Project p");
		return query.getResultList();
	}

	@Override
	public Project findProjectById(final int id) throws ProjectNotFoundException {
		final Project ret = this.manager.find(Project.class, id);
		if (ret == null) {
			throw new ProjectNotFoundException();
		}

		return ret;
	}

	@Override
	public void addMilestone(final int projectId, final Milestone milestone) throws ProjectNotFoundException {
		findProjectById(projectId).addMilestone(milestone);
	}

}
